// 股票数据API服务

const API_BASE_URL = 'http://localhost:8000/api';

export interface StockInfo {
  symbol: string;
  name: string;
  current_price: number;
  change: number;
  change_percent: number;
  volume: number;
  turnover: number;
}

export interface StockHistoryData {
  date: string;
  open: number;
  high: number;
  low: number;
  close: number;
  volume: number;
}

export interface StockHistory {
  symbol: string;
  name: string;
  period: string;
  data: StockHistoryData[];
}

export interface AnalysisResult {
  period: string;
  similarity: number;
  start_price: number;
  end_price: number;
  change_percent: number;
}

export interface StockAnalysis {
  symbol: string;
  name: string;
  analysis_period: number;
  results: AnalysisResult[];
}

export interface ComparisonData {
  day: number;
  date: string;
  price: number;
  change_percent: number;
}

export interface StockComparison {
  symbol: string;
  name: string;
  current_period: {
    start_date: string;
    end_date: string;
    data: ComparisonData[];
  };
  historical_period: {
    start_date: string;
    end_date: string;
    data: ComparisonData[];
  };
}

class StockApiService {
  private async fetchWithTimeout(url: string, options: RequestInit = {}, timeout = 10000, retries = 3): Promise<Response> {
    let lastError: Error | null = null;
    
    for (let attempt = 0; attempt <= retries; attempt++) {
      const controller = new AbortController();
      let timeoutId: NodeJS.Timeout | null = null;
      
      try {
        // 设置超时
        timeoutId = setTimeout(() => {
          controller.abort();
        }, timeout);
        
        const response = await fetch(url, {
          ...options,
          signal: controller.signal,
        });
        
        // 清除超时
        if (timeoutId) {
          clearTimeout(timeoutId);
          timeoutId = null;
        }
        
        return response;
      } catch (error) {
        // 清除超时
        if (timeoutId) {
          clearTimeout(timeoutId);
          timeoutId = null;
        }
        
        lastError = error instanceof Error ? error : new Error(String(error));
        
        // 如果是最后一次尝试，直接抛出错误
        if (attempt === retries) {
          break;
        }
        
        // 检查错误类型，决定是否重试
        if (lastError.name === 'AbortError') {
          console.warn(`Request timeout on attempt ${attempt + 1}, retrying...`);
          // 超时错误，等待一段时间后重试
          await new Promise(resolve => setTimeout(resolve, 1000 * (attempt + 1)));
        } else if (lastError.message.includes('fetch')) {
          console.warn(`Network error on attempt ${attempt + 1}, retrying...`);
          // 网络错误，等待一段时间后重试
          await new Promise(resolve => setTimeout(resolve, 500 * (attempt + 1)));
        } else {
          // 其他错误，直接抛出
          break;
        }
      }
    }
    
    // 抛出最后一个错误，但提供更友好的错误信息
    if (lastError) {
      if (lastError.name === 'AbortError') {
        throw new Error('请求超时，请检查网络连接或稍后重试');
      } else if (lastError.message.includes('fetch')) {
        throw new Error('网络连接失败，请检查网络设置');
      } else {
        throw lastError;
      }
    }
    
    throw new Error('请求失败，未知错误');
  }

  private async handleResponse<T>(response: Response): Promise<T> {
    if (!response.ok) {
      const errorText = await response.text();
      throw new Error(`API Error: ${response.status} - ${errorText}`);
    }
    return response.json();
  }

  async getStockInfo(symbol: string): Promise<StockInfo> {
    try {
      const response = await this.fetchWithTimeout(
        `${API_BASE_URL}/stock/info/${symbol}`,
        {},
        8000, // 8秒超时
        2 // 重试2次
      );
      return this.handleResponse<StockInfo>(response);
    } catch (error) {
      console.error('Failed to fetch stock info:', error);
      throw new Error(`获取股票信息失败: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  }

  async getStockHistory(
    symbol: string,
    period: string = 'daily',
    startDate?: string,
    endDate?: string
  ): Promise<StockHistory> {
    try {
      const params = new URLSearchParams({
        period,
        ...(startDate && { start_date: startDate }),
        ...(endDate && { end_date: endDate }),
      });
      
      const response = await this.fetchWithTimeout(
        `${API_BASE_URL}/stock/history/${symbol}?${params}`,
        {},
        20000, // 20秒超时，历史数据需要更长时间
        3 // 重试3次
      );
      return this.handleResponse<StockHistory>(response);
    } catch (error) {
      console.error('Failed to fetch stock history:', error);
      throw new Error(`获取股票历史数据失败: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  }

  async getStockAnalysis(symbol: string, days: number = 30): Promise<StockAnalysis> {
    try {
      const response = await this.fetchWithTimeout(
        `${API_BASE_URL}/stock/analysis/${symbol}?days=${days}`,
        {},
        25000, // 25秒超时，分析需要更长时间
        2 // 重试2次
      );
      return this.handleResponse<StockAnalysis>(response);
    } catch (error) {
      console.error('Failed to fetch stock analysis:', error);
      throw new Error(`获取股票分析失败: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  }

  async getStockComparison(
    symbol: string,
    targetPeriod: string,
    days: number = 30
  ): Promise<StockComparison> {
    try {
      const params = new URLSearchParams({
        target_period: targetPeriod,
        days: days.toString(),
      });
      
      const response = await this.fetchWithTimeout(
        `${API_BASE_URL}/stock/comparison/${symbol}?${params}`,
        {},
        18000, // 18秒超时
        3 // 重试3次
      );
      return this.handleResponse<StockComparison>(response);
    } catch (error) {
      console.error('Failed to fetch stock comparison:', error);
      throw new Error(`获取股票对比数据失败: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  }

  // 检查API服务是否可用
  async checkApiHealth(): Promise<boolean> {
    try {
      // 使用一个简单的API端点来检查服务状态
      const response = await this.fetchWithTimeout(
        `${API_BASE_URL}/health`,
        {},
        6000, // 6秒超时
        1 // 只重试1次
      );
      return response.ok;
    } catch (error) {
      console.error('API health check failed:', error);
      // 如果健康检查失败，尝试直接测试一个股票信息接口
      try {
        const testResponse = await this.fetchWithTimeout(
          `${API_BASE_URL}/stock/info/000001`,
          {},
          5000, // 5秒超时
          1 // 只重试1次
        );
        return testResponse.ok;
      } catch (testError) {
        console.error('Fallback API test failed:', testError);
        return false;
      }
    }
  }
}

// 导出单例实例
export const stockApi = new StockApiService();

// 导出类型和服务
export default stockApi;